import axio from 'axios'
import router from '@/routes'
import { Toast } from 'vant';
import appConfig from '@/config';

const instance = axio.create({
  timeout: 1000 * 60 * 10,
})

console.log('url', appConfig.baseUrl);

instance.interceptors.request.use(
  (config) => {
    const token = sessionStorage.getItem('accessToken') || ''
    let headers = {
      ...config.headers,
      accessToken: token,
      loginType: config.manager ? 'MANGER' : 'MANGER',
    }
    headers['x-access-token'] = token
    return {
      ...config,
      url: appConfig.baseUrl + config.url,
      headers: headers,
    }
  },
  (error) => {
    return Promise.reject(error)
  },
)

instance.interceptors.response.use(
  (response) => {
    if (response.data.code === 1001) {
      Toast('登录已失效，请重新登录 ')
      sessionStorage.removeItem("accessToken")
      router.push('/login')
      return
    }
    return response
  },
  (error) => {
    const errJson = error.toJSON()
    if (errJson.status === 403) {
      // 登录已失效，请重新登录 
      Toast('登录已失效，请重新登录 ')
      // ElMessage({
      //   message: '登录已失效，请重新登录',
      //   type: 'error',
      // })

      sessionStorage.removeItem("accessToken");
      router.push('/login')

      return
    }
    Toast('系统繁忙，请重试')
    return Promise.reject(error)
  }
)

const request = async (url, config) => {
  const { data } = await instance.request({
    url,
    ...config,
  })
  if (data.code !== 1) {
    Toast(data.msg);
  }
  return Promise.resolve(data)
}

export default request
